package com.lkd.handler;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.emq.Topic;
import com.lkd.entity.VendingMachineEntity;
import com.lkd.service.VendingMachineService;
import com.lkd.utils.JsonUtil;
import io.micrometer.core.instrument.util.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONArray;
import org.springframework.stereotype.Component;

import java.io.IOException;


@Component
@Topic(TopicConfig.VMS_SUPPLY_TOPIC)
public class TaskCompleteHandler implements MsgHandler {
    @Autowired
    private VendingMachineService vendingMachineService;

    @Override
    public void process(String jsonMsg) throws IOException {
        //将接收到的JSON类型消息解析为TaskCompleteContract类
        TaskCompleteContract contract = JsonUtil.getByJson(jsonMsg, TaskCompleteContract.class);
        //获取消息传递的工单类型
        int taskType = contract.getTaskType();
        //获取机器编号
        String innerCode = contract.getInnerCode();


        //根据传递来的机器编号获取到售货机详情
        LambdaQueryWrapper<VendingMachineEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(VendingMachineEntity::getInnerCode, innerCode);
        VendingMachineEntity vendingMachineEntity = vendingMachineService.getOne(queryWrapper);
        //更新售货机状态
        if (taskType == VMSystem.TASK_TYPE_DEPLOY) {
            //如果完成的工单为投放工单，则售货机状态更新为运营中
            vendingMachineEntity.setVmStatus(VMSystem.VM_STATUS_RUNNING);
        }else if (taskType == VMSystem.TASK_TYPE_REVOKE){
            //如果工单为撤机工单，则售货机状态更新为撤机状态
            vendingMachineEntity.setVmStatus(VMSystem.VM_STATUS_REVOKE);
        }

        //更改售货机状态
        vendingMachineService.updateById(vendingMachineEntity);
    }
}
